package com.springboot.springtest.Util;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author wwj
 * @date 2021/3/12 0012 17:39
 */
@Controller
@RequestMapping(value = "/upload")
public class upload {
    //可以将此处的代码放入工具类中
    @PostMapping(value = "/test")
    public String upload(@RequestParam("file") MultipartFile file ) throws IOException {
        try {
            if (file.isEmpty()) {
                System.out.println("文件不能为空");
            }
            //获取文件原始名
            String fileName = file.getOriginalFilename();
            //获取后缀名
            String suffixName = fileName.substring(fileName.lastIndexOf("."), fileName.length());
            System.out.println("文件名" + fileName + "后缀名" + suffixName);
            //设置文件存放位置
            String filePath = "D:\\";
            String path = filePath + fileName;
            File dest = new File(path);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdir();//新建文件夹
            }
            file.transferTo(dest);//写入
            return "userList";
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "ok";
    }
    }
